package com.xand.mtgox.connector;

import io.socket.SocketIO;

import java.util.List;
import java.util.logging.Level;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xand.bt.api.MarketConnector;
import com.xand.bt.api.MarketImageChangeNotify;

public class MtGoxConnector implements MarketConnector {

	public static final String MARKET_LABEL = "MTGOX";
	
	private static final Logger logger = LoggerFactory.getLogger(MtGoxConnector.class);
	
	public MtGoxConnector() {
		this.startConnector();
	}
	
	public void startConnector() {
		
		java.util.logging.Logger loggerIOSocket = java.util.logging.Logger.getLogger("io.socket"); 
		loggerIOSocket.setLevel(Level.SEVERE);
		
		SocketIO socket = null;
		
		try {
			
			socket = new SocketIO("http://socketio.mtgox.com/mtgox");
			
		}catch(Exception e){
			
			logger.error("An error occured", e);
			throw new RuntimeException(e);
			
		}
		
		MtGoxIOCallback callback = new MtGoxIOCallback();
		
		socket.connect(callback);
		
		// wait for 10 seconds
		logger.info("Waiting for 120 seconds...");
		try {
			
			Thread.sleep(120000);
			
		}catch(Exception e){
			
			logger.error("An error occured", e);
			throw new RuntimeException(e);
			
		}
		logger.info("Wait is done, starting synchronization.");
		
		MtGoxSynchronizer sync = new MtGoxSynchronizer();
		
		try {
			
			long start = System.currentTimeMillis();
			
			sync.loadFullMarketDepth();
			
			long delta = System.currentTimeMillis() - start;
			
			logger.info("Full market depth load completed in " + delta + "ms");
			
			start = System.currentTimeMillis();
			
			synchronized(SyncLock.LOCK) {
				// we stop processing of any messages
				
				TemporaryMarketImageChangesStore tmpStore = callback.getTemporaryMarketImageChangesStore();
				sync.processPendingMessages(tmpStore);
				
				// clear tmp store
				tmpStore.clear();
				
				// synchronization is done
				MtGoxMarketChangesStore store = MtGoxMarketChangesStore.getInstance();
				store.setSynchronizationDone(true);
			}
			
			delta = System.currentTimeMillis() - start;
			
			logger.info("Pending market processed in " + delta + "ms");
			
		}catch(Exception e){
			
			logger.error("An error occured", e);
			throw new RuntimeException(e);
			
		}
		
	}
	
	public List<MarketImageChangeNotify> getMarketImageChanges() {
		
		MtGoxMarketChangesStore store = MtGoxMarketChangesStore.getInstance();
		
		List<MarketImageChangeNotify> ret = store.getMarketChanges();
		
		return ret;
	}
	
}
